//
//  WorkHomeVC.m
//  XLDoctor
//
//  Created by longma on 2018/7/27.
//  Copyright © 2018年 XLH. All rights reserved.
//mj登录

#import "LoginPasswordVC.h"
#import "LanguageController.h"
#import "CountryCodeVC.h"
#import "RegisterViewController.h"
#import "AllCountryCodeVC.h"
#import "NBPhoneNumberUtil.h"
#import "EnterCodeController.h"
#import "CaptchaView.h"
#import "MJConfirmLoadingView.h"
#import "LoginViewController.h"
#import "ForgotPasswordVC.h"
#import "LoginEmailVC.h"

@interface LoginPasswordVC ()
@property (weak, nonatomic) IBOutlet UILabel *countryCodeLabel;
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;
@property (weak, nonatomic) IBOutlet MJUITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet MJConfirmLoadingView *confirmButton;
@property (weak, nonatomic) IBOutlet UIView *phoneNumberBgView;
@property (nonatomic, strong) NSDictionary *countryAreaCode;
@property (weak, nonatomic) IBOutlet UIButton *encryptButton;
@property (weak, nonatomic) IBOutlet MJUITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (nonatomic, assign) BOOL phoneNumberDidBegin;
@property (nonatomic, assign) BOOL passwordDidBegin;
@property (nonatomic, assign) NSInteger errorPasswordCount;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *forgotButtonW;
@property (weak, nonatomic) IBOutlet UIButton *forgotButton;

@end

@implementation LoginPasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
 
    //更新版本
    [HealthHelper appUpgradeWithToast:false];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    CGSize forgotButtonSize = [self.forgotButton sizeThatFits:CGSizeMake(MAXFLOAT, 60)];
    CGFloat fHeight = forgotButtonSize.width + 30;
    if(fHeight > 85){
        self.forgotButtonW.constant = fHeight;
    }else{
        self.forgotButtonW.constant = 85;
    }
}

- (void)mj_setUI{
    [super mj_setUI];
    
    [self.navigationController setNavigationBarHidden:true animated:NO];
    
//    self.forgotButton.titleLabel.adjustsFontSizeToFitWidth = true;

    self.phoneNumberTextField.mj_disableThirdPartyKeyboard = true;
    self.phoneNumberTextField.font = MJUIFontMake(20);
    
    self.tipLabel.hidden = true;
    self.countryCodeLabel.text = @"";

    self.countryAreaCode = [HealthHelper getCountryAreaCode];
    NSString *code = [NSString stringWithFormat:@"+%@",self.countryAreaCode[@"区号"]];
    self.countryCodeLabel.text = code;
    
    if([self.countryCodeLabel.text containsString:@"+86"]){
        self.phoneNumberTextField.mj_limitedNumber = 11;
    }
    
    NBPhoneNumberUtil *phoneUtil = [NBPhoneNumberUtil sharedInstance];
    MJWeakSelf
    RAC(self.confirmButton, enabled) = [RACSignal combineLatest:@[self.phoneNumberTextField.rac_textSignal,RACObserve(self.phoneNumberTextField, text),self.passwordTextField.rac_textSignal] reduce:^id _Nullable(NSString * text,NSString * phone,NSString * password){
        
        BOOL enable = false;
        if([self.countryCodeLabel.text containsString:@"+86"]){
            if(text.length == 11 && [text mj_isMobileNumber]){
                enable = true;
            }else{
                enable = false;
            }
        }else{
            NBPhoneNumber *myNumber = [phoneUtil parse:text
                                          defaultRegion:weakSelf.countryAreaCode[@"ISO"] error:nil];
            enable = [phoneUtil isValidNumber:myNumber];
            NSLog(@"isValidPhoneNumber ? [%@]", [phoneUtil isValidNumber:myNumber] ? @"YES":@"NO");
        }
      
        if(enable && weakSelf.passwordDidBegin){
            weakSelf.tipLabel.hidden = true;
        }
        
        if(enable && password.length >= 6){
            return @(true);
        }else{
            return @(false);
        }
    }];
 
    self.confirmButton.handleContinueBlock = ^{
        [weakSelf handleConfirmButtonClick];
    };
    //
    [self.encryptButton setImage:MJUIImageMake(@"icon_biyan_p") forState:0];
    [self.encryptButton setImage:MJUIImageMake(@"icon_zhengyan_p") forState:UIControlStateSelected];
    [self.confirmButton.continueButton setTitle:MJUILocalizedString(@"Log in") forState:0];
    self.passwordTextField.secureTextEntry = true;
    
//    CGSize forgotButtonSize = [self.forgotButton sizeThatFits:CGSizeMake(MAXFLOAT, 60)];
//    self.forgotButtonW.constant = forgotButtonSize.width + 20;
//    self.forgotButtonW.constant = 60;

    [[self.phoneNumberTextField rac_signalForControlEvents:UIControlEventEditingDidBegin] subscribeNext:^(__kindof UITextField * _Nullable x) {
        weakSelf.phoneNumberDidBegin = true;
        weakSelf.phoneNumberTextField.text = weakSelf.phoneNumberTextField.text;
        [weakSelf.phoneNumberBgView mj_borderColor:UIColor.mj_appColor width:2];

    }];
    [[self.phoneNumberTextField rac_signalForControlEvents:UIControlEventEditingDidEnd] subscribeNext:^(__kindof UITextField * _Nullable x) {
        weakSelf.phoneNumberDidBegin = false;
        
        NSString *phone = weakSelf.phoneNumberTextField.text;
        BOOL enable = false;
        if([self.countryCodeLabel.text containsString:@"+86"]){
            if(phone.length == 11 && [phone mj_isMobileNumber]){
                enable = true;
            }else{
                enable = false;
            }
        }else{
            NBPhoneNumber *myNumber = [phoneUtil parse:phone
                                          defaultRegion:weakSelf.countryAreaCode[@"ISO"] error:nil];
            enable = [phoneUtil isValidNumber:myNumber];
            NSLog(@"isValidPhoneNumber ? [%@]", [phoneUtil isValidNumber:myNumber] ? @"YES":@"NO");
        }
        //判断手机号码是否合规
        if(phone.length > 0 && !enable){
            [weakSelf.phoneNumberBgView mj_borderColor:UIColor.mj_redColor width:2];
            weakSelf.tipLabel.hidden = false;
            weakSelf.tipLabel.mj_localizable = @"Invalid phone number";
        }else{
            weakSelf.tipLabel.hidden = true;
            [weakSelf.phoneNumberBgView mj_borderColor:UIColor.clearColor width:2];
        }
        
    }];
    
    [[self.passwordTextField rac_signalForControlEvents:UIControlEventEditingDidBegin] subscribeNext:^(__kindof UITextField * _Nullable x) {
        weakSelf.passwordDidBegin = true;

        [weakSelf.passwordView mj_borderColor:UIColor.mj_appColor width:2];
    }];
    [[self.passwordTextField rac_signalForControlEvents:UIControlEventEditingDidEnd] subscribeNext:^(__kindof UITextField * _Nullable x) {
        weakSelf.passwordDidBegin = false;
        [weakSelf.passwordView mj_borderColor:UIColor.clearColor width:2];
    }];

}

#pragma mark - 方法
- (void)requestData{
    
}

- (IBAction)handleForgotButtonClick:(UIButton *)sender {
    
    ForgotPasswordVC *vc = [[ForgotPasswordVC alloc]init];
    vc.countryAreaCode = self.countryAreaCode;
    vc.phoneNumber = self.phoneNumberTextField.text;
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)handleEncryptButtonClick:(UIButton *)sender {
    [self.encryptButton setSelected:!sender.isSelected];
    
    if(sender.isSelected){
        self.passwordTextField.secureTextEntry = false;
    }else{
        self.passwordTextField.secureTextEntry = true;
    }
}
- (IBAction)handleLanguageButtonClick:(UIButton *)sender {
    LanguageController *vc = [[LanguageController alloc]init];
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)handleEmailPasswordLoginButtonClick:(UIButton *)sender {
   
    LoginEmailVC *loginVC = [[LoginEmailVC alloc]init];
    BasicNavigationController * nav = [[BasicNavigationController alloc]initWithRootViewController:loginVC];
    AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
    appDelegate.window.rootViewController = nav;
}

- (IBAction)handleVerificationCodeLoginButtonClick:(UIButton *)sender {
    LoginViewController *vc = [[LoginViewController alloc]init];
    vc.countryAreaCode = self.countryAreaCode;
    vc.phoneNumber = self.phoneNumberTextField.text;
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)handleRegisterButtonClick:(UIButton *)sender {
    RegisterViewController *vc = [[RegisterViewController alloc]init];
    vc.countryAreaCode = self.countryAreaCode;
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)handleCountryCodeButtonClick:(UIButton *)sender {
    MJWeakSelf
    AllCountryCodeVC *vc = [[AllCountryCodeVC alloc]init];
    vc.handleCountryCodeBlock = ^(NSDictionary *countryAreaCode) {
        NSString *code = [NSString stringWithFormat:@"+%@",countryAreaCode[@"区号"]];
        weakSelf.countryCodeLabel.text = code;
        weakSelf.countryAreaCode = countryAreaCode;

    };
    [self.navigationController pushViewController:vc animated:true];
}

- (void)handleConfirmButtonClick {
    [self.phoneNumberTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];

    NSString *password = [HealthHelper aesEncryptString:self.passwordTextField.text];

    NSDictionary *params =  @{
        @"countryCode": self.countryAreaCode[@"区号"],
        @"phoneNumber": self.phoneNumberTextField.text,
        @"region": self.countryAreaCode[@"ISO"],
        @"loginType": @"iOS",
        @"password": password,
    };
    MJWeakSelf
    [MJHttpNetWorking requestWithParams:params requestUri:user_loginByPassword requestType:RequestTypePost showLoading:false success:^(MJBaseModel *model) {
        
        [weakSelf.confirmButton.loadingView stopAnimation];
        if(model.code == 200){
            if(model.data){
                [UserManager.shared saveUserInfo:model.data];
                AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
                [appDelegate initRootViewController];
                [RoyHud showToast:MJUILocalizedString(@"Log in successful")];
            }else{
                [weakSelf noRegisterAlert];
            }
        }else if(model.code == 417){
//            weakSelf.tipLabel.mj_localizable = @"Enter a vaild phone number";
//            weakSelf.tipLabel.hidden = false;
            
            //如果输入密码错误次数≥5，则弹出此弹窗
            weakSelf.errorPasswordCount = weakSelf.errorPasswordCount + 1;
            if(weakSelf.errorPasswordCount >= 5){
                [weakSelf showMaxAttemptsView];
            }else{
                weakSelf.tipLabel.hidden = false;
                weakSelf.tipLabel.mj_localizable = @"Invalid password";
                [weakSelf.passwordView mj_borderColor:UIColor.mj_redColor width:2];
            }
            
        }else if(model.code == 412){
            
            [weakSelf noRegisterAlert];

        }

    } failure:^(NSError *error) {
        [weakSelf.confirmButton.loadingView stopAnimation];

    }];

}
- (void)noRegisterAlert {
    [self.phoneNumberTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    //未注册
    MJWeakSelf
    MJUIAlertViewConfigure *configure = [[MJUIAlertViewConfigure alloc]init];
    configure.confirmButtonColor = UIColor.mj_appColor;
    configure.confirmTitle = MJUILocalizedString(@"OK_qd");
    configure.cancelTitle = MJUILocalizedString(@"Cancel_qx");
    configure.messageAlignmentCenter = true;
    NSString *messageString = MJUILocalizedString(@"The number is not registered. Sign up for a new account now?");
    [MJUIAlertView alertViewWithTitle:MJUILocalizedString(@"Phone Number Not Registered") message:messageString configure:configure confirmBlock:^{
        RegisterViewController *vc = [[RegisterViewController alloc]init];
        vc.phoneNumber = weakSelf.phoneNumberTextField.text;
        vc.countryAreaCode = weakSelf.countryAreaCode;
        [weakSelf.navigationController pushViewController:vc animated:true];
    } cancelBlock:^{

    }];
}
/// 密码错误次数≥5，则弹出此弹窗
- (void)showMaxAttemptsView {
    
    MJWeakSelf
    MJUIAlertViewConfigure *configure = [[MJUIAlertViewConfigure alloc]init];
    configure.confirmButtonColor = UIColor.mj_appColor;
    configure.confirmTitle = MJUILocalizedString(@"Try_Again_cs");
    configure.cancelTitle = MJUILocalizedString(@"Login via Code");
    configure.messageAlignmentCenter = true;
    configure.disableDismissWindow = true;
    NSString *messageString = MJUILocalizedString(@"Password attempts exceeded the limit. Please try again in 3 minutes, or log in via a verification code.");
    [MJUIAlertView alertViewWithTitle:MJUILocalizedString(@"Max Attempts") message:messageString configure:configure confirmBlock:^{
        [weakSelf.confirmButton startCountdown];

    } cancelBlock:^{
        [weakSelf.confirmButton startCountdown];
        [weakSelf handleVerificationCodeLoginButtonClick:nil];
    }];

}

/// 滑块验证码
- (void)sendAnjCcaptchaCode {
    
    MJWeakSelf
    [CaptchaView showWithType: puzzle CompleteBlock:^(NSString *  result) {
        
        [weakSelf.confirmButton.loadingView startAnimation];

        NSLog(@"result=======================%@",result);
        NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:@{
            @"countryCode": self.countryAreaCode[@"区号"],
            @"phoneNumber": self.phoneNumberTextField.text,
            @"region": self.countryAreaCode[@"ISO"],
            @"code": result,
        }];
        [MJHttpNetWorking requestWithParams:parms requestUri:captcha_sendSms requestType:RequestTypePost showLoading:false success:^(MJBaseModel *model) {
            [weakSelf.confirmButton.loadingView stopAnimation];

            if (model.code ==  200){
                
                EnterCodeController *vc = [[EnterCodeController alloc]init];
                vc.phone = weakSelf.phoneNumberTextField.text;
                vc.countryAreaCode = weakSelf.countryAreaCode;
                [weakSelf.navigationController pushViewController:vc animated:true];
            }else if(model.code ==  412){
                [RoyHud showToast:MJUILocalizedString(@"Too frequent, Retry later.")];
            }
            
        } failure:^(NSError *error) {
            [weakSelf.confirmButton.loadingView stopAnimation];

        }];
    }];
}

#pragma mark - 代理

#pragma mark - 懒加载
- (void)mj_setUIxxxxxx{
    [super mj_setUI];
    
    [self.navigationController setNavigationBarHidden:true animated:NO];

    self.phoneNumberTextField.mj_disableThirdPartyKeyboard = true;
    self.phoneNumberTextField.font = MJUIFontMake(20);
    
    self.tipLabel.hidden = true;
    self.countryCodeLabel.text = @"";

    self.countryAreaCode = [HealthHelper getCountryAreaCode];
    NSString *code = [NSString stringWithFormat:@"+%@",self.countryAreaCode[@"区号"]];
    self.countryCodeLabel.text = code;
    
    if([self.countryCodeLabel.text containsString:@"+86"]){
        self.phoneNumberTextField.mj_limitedNumber = 11;
    }
    
    NBPhoneNumberUtil *phoneUtil = [NBPhoneNumberUtil sharedInstance];
    MJWeakSelf
    RAC(self.confirmButton, enabled) = [RACSignal combineLatest:@[self.phoneNumberTextField.rac_textSignal,RACObserve(self.phoneNumberTextField, text),self.passwordTextField.rac_textSignal] reduce:^id _Nullable(NSString * text,NSString * phone,NSString * password){
        
        BOOL enable = false;
        if([self.countryCodeLabel.text containsString:@"+86"]){
            if(text.length == 11 && [text mj_isMobileNumber]){
                enable = true;
            }else{
                enable = false;
            }
        }else{
            NBPhoneNumber *myNumber = [phoneUtil parse:text
                                          defaultRegion:weakSelf.countryAreaCode[@"ISO"] error:nil];
            enable = [phoneUtil isValidNumber:myNumber];
            NSLog(@"isValidPhoneNumber ? [%@]", [phoneUtil isValidNumber:myNumber] ? @"YES":@"NO");
        }
      
        if(enable && weakSelf.phoneNumberDidBegin){
            [weakSelf.phoneNumberBgView mj_borderColor:UIColor.mj_appColor width:2];
        }else{
            [weakSelf.phoneNumberBgView mj_borderColor:UIColor.clearColor width:2];
            weakSelf.tipLabel.hidden = true;
        }
        
        if(enable && password.length >= 6){
            return @(true);
        }else{
            return @(false);
        }
        
//        return @(enable);
    }];
 
    self.confirmButton.handleContinueBlock = ^{
        [weakSelf handleConfirmButtonClick];

    };
    //
    [self.encryptButton setImage:MJUIImageMake(@"icon_biyan_p") forState:0];
    [self.encryptButton setImage:MJUIImageMake(@"icon_zhengyan_p") forState:UIControlStateSelected];
    [self.confirmButton.continueButton setTitle:MJUILocalizedString(@"Log in") forState:0];
    self.passwordTextField.secureTextEntry = true;
    
    CGSize forgotButtonSize = [self.forgotButton sizeThatFits:CGSizeMake(MAXFLOAT, 60)];
//    self.forgotButtonW.constant = forgotButtonSize.width + 20;
    self.forgotButtonW.constant = 60;

    [[self.phoneNumberTextField rac_signalForControlEvents:UIControlEventEditingDidBegin] subscribeNext:^(__kindof UITextField * _Nullable x) {
        weakSelf.phoneNumberDidBegin = true;
        weakSelf.phoneNumberTextField.text = weakSelf.phoneNumberTextField.text;
    }];
    [[self.phoneNumberTextField rac_signalForControlEvents:UIControlEventEditingDidEnd] subscribeNext:^(__kindof UITextField * _Nullable x) {
        weakSelf.phoneNumberDidBegin = false;
        [weakSelf.phoneNumberBgView mj_borderColor:UIColor.clearColor width:2];
    }];
    
    [[self.passwordTextField rac_signalForControlEvents:UIControlEventEditingDidBegin] subscribeNext:^(__kindof UITextField * _Nullable x) {
        [weakSelf.passwordView mj_borderColor:UIColor.mj_appColor width:2];
    }];
    [[self.passwordTextField rac_signalForControlEvents:UIControlEventEditingDidEnd] subscribeNext:^(__kindof UITextField * _Nullable x) {
        [weakSelf.passwordView mj_borderColor:UIColor.clearColor width:2];
    }];
    
//    [self showMaxAttemptsView];
    
//    [self mj_pushViewController:@"EnterCodeController"];
//    [self handleCountryCodeButtonClick:nil];
//    [self sendAnjCcaptchaCode];
//    self.phoneNumberTextField.text = @"15819953627";

}
@end
